package com.qst.mapreduce.wordcount.zuoyemywc.zajiaoban;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class MaxTemperatureCounter {

    // Mapper类
    public static class TempMapper
            extends Mapper<Object, Text, IntWritable, IntWritable> {

        private final static IntWritable one = new IntWritable(1);
        private IntWritable maxTemp = new IntWritable();

        public void map(Object key, Text value, Context context
        ) throws IOException, InterruptedException {
            // 分割CSV格式数据
            String[] tokens = value.toString().split(",");
            if (tokens.length >= 3) {
                try {
                    int temperature = Integer.parseInt(tokens[2].trim());
                    maxTemp.set(temperature);
                    context.write(maxTemp, one); // 输出 (最高温度, 1)
                } catch (NumberFormatException e) {
                    // 忽略无效温度数据
                }
            }
        }
    }

    // Reducer类
    public static class TempReducer
            extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {

        private IntWritable result = new IntWritable();

        public void reduce(IntWritable key, Iterable<IntWritable> values,
                           Context context
        ) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get(); // 累加出现次数
            }
            result.set(sum);
            context.write(key, result); // 输出 (温度, 总天数)
        }
    }

    // 驱动类
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "max temperature count");
        job.setJarByClass(MaxTemperatureCounter.class);

        job.setMapperClass(TempMapper.class);
        job.setCombinerClass(TempReducer.class);
        job.setReducerClass(TempReducer.class);

        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.addInputPath(job, new Path("E:\\changyongruanjian\\dashujuJava\\JavaAPPneirong\\shujukucode\\MapReduceDemo\\MapReduceDemo\\input\\word.txt"));
        FileOutputFormat.setOutputPath(job, new Path("E:\\changyongruanjian\\dashujuJava\\JavaAPPneirong\\shujukucode\\MapReduceDemo\\MapReduceDemo\\output"));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}